#C 语言标准库头文件 stdio.h
这个头文件提供 标准输入输出 的相关功能。例如打印显示内容,读取命令行输入等。
#示例
#include <stdio.h> // 包含标准输入输出头文件
int main(void) {
// 1. 使用 printf 输出到标准输出
printf("Hello, World!\n");
// 2. 格式化输出
int age = 25;
float height = 1.75f;
printf("I am %d years old and %.2f meters tall.\n", age, height);
// 3. 从标准输入读取数据
char name[50];
printf("Please enter your name: ");
scanf("%49s", name); // 限制输入长度为49个字符,防止缓冲区溢出
printf("Hello, %s!\n", name);
getchar(); // 读取换行符
// 4. 文件操作
FILE *file = fopen("example.txt", "w"); // 以写入模式打开文件
if (file != NULL) {
fprintf(file, "This is written to a file.\n");
fclose(file); // 关闭文件
} else {
perror("Failed to open file"); // 打印错误信息
}
// 5. 读取文件内容
file = fopen("example.txt", "r");
if (file != NULL) {
char buffer[100];
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("File content: %s", buffer);
}
fclose(file);
}
// 6. 使用 putchar 和 getchar
printf("Enter a character: ");
int ch = getchar(); // 读取一个字符
printf("You entered: ");
putchar(ch); // 输出一个字符
putchar('\n');
// 7. 清空输入缓冲区
while ((ch = getchar()) != '\n' && ch != EOF); // 清除剩余输入
return 0;
}
运行结果:
Hello, World! I am 25 years old and 1.75 meters tall. Please enter your name: planc Hello, planc! File content: This is written to a file. Enter a character: A You entered: A